package com.cloudpivot.receivales.invoice.services;

import com.alibaba.fastjson.JSONObject;
import com.cloudpivot.receivales.contract.service.http.HttpAPIServiceForCrm;
import com.cloudpivot.receivales.invoice.bsweaverws.*;
import com.cloudpivot.receivales.invoice.pojo.KaiPiaoItemPOJO;
import com.cloudpivot.receivales.invoice.pojo.KaiPiaoItemTowPOJO;
import com.cloudpivot.receivales.invoice.pojo.KaiPiaoPOJO;
import com.cloudpivot.receivales.invoice.pojo.ResultInfo;
import com.cloudpivot.receivales.invoice.view.FaPiaoLXEnum;
import com.cloudpivot.receivales.invoice.view.KaiPiaoGSEnum;
import com.cloudpivot.receivales.invoice.view.KaiPiaoLXEnum;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * oa流程服务
 */
@Service
@Slf4j
public class OAWorkflowServiceImpl {

    @Value("${myprops.oawsurl}")
    private String oawsurl;

    @Autowired
    private HttpAPIServiceForCrm httpApi;

    @Value("${myprops.smdurl}")
    private String smdurl;

    @Autowired
    private ObjectMapper objectMapper;


    /**
     * 新建开票退票流程
     */
    public ResultInfo createWorkflow(KaiPiaoPOJO pojo) throws Exception {
        //人名的转换
        String userid=getOaId(pojo.getShenqingr());
        String departmentid=getDepartmentid(pojo.getShenqingr());
        // 接收流程信息
        ResultInfo resultInfo = new ResultInfo();

        if(StringUtils.isBlank(userid)){
            log.info("未获取到用户名，请检查手机号是否正确！");
            resultInfo.setFlowNum("-101");
            return resultInfo;
        }
        //创建主表字段\转化
        WorkflowRequestTableField[] wfrtf = new WorkflowRequestTableField[17];
        //标题
        wfrtf[0] = new WorkflowRequestTableField();
        wfrtf[0].setFieldName("biaoti");
        wfrtf[0].setFieldValue(pojo.getBiaoti());
        wfrtf[0].setView(true);
        wfrtf[0].setEdit(true);
        //申请人
        wfrtf[1] = new WorkflowRequestTableField();
        wfrtf[1].setFieldName("shenqingr");
        wfrtf[1].setFieldValue(userid);
        wfrtf[1].setView(true);
        wfrtf[1].setEdit(true);

        //开票类别
        wfrtf[2] = new WorkflowRequestTableField();
        wfrtf[2].setFieldName("kaipiaolb");
        wfrtf[2].setFieldValue(KaiPiaoLXEnum.getKey(pojo.getKaipiaolb()));
        wfrtf[2].setView(true);
        wfrtf[2].setEdit(true);
        //发票类型
        wfrtf[3] = new WorkflowRequestTableField();
        wfrtf[3].setFieldName("fahuolx");
        wfrtf[3].setFieldValue(FaPiaoLXEnum.getKey(pojo.getFapiaolx()));
        wfrtf[3].setView(true);
        wfrtf[3].setEdit(true);
        //开票总金额
        wfrtf[4] = new WorkflowRequestTableField();
        wfrtf[4].setFieldName("kaipiaozje");
        wfrtf[4].setFieldValue(pojo.getKaipiaozje().toString());
        wfrtf[4].setView(true);
        wfrtf[4].setEdit(true);
        //是否需要出库单=0
        wfrtf[5] = new WorkflowRequestTableField();
        wfrtf[5].setFieldName("shigouxyckd");
        wfrtf[5].setFieldValue("1");
        wfrtf[5].setView(true);
        wfrtf[5].setEdit(true);
        //收件人信息
        wfrtf[6] = new WorkflowRequestTableField();
        wfrtf[6].setFieldName("shoujianrxx");
        wfrtf[6].setFieldValue(pojo.getShoujianrxx());
        wfrtf[6].setView(true);
        wfrtf[6].setEdit(true);
        //流程文档
        wfrtf[7] = new WorkflowRequestTableField();
        wfrtf[7].setFieldName("liuchengwd");
        wfrtf[7].setFieldValue(pojo.getLiuchengwd());
        wfrtf[7].setView(true);
        wfrtf[7].setEdit(true);
        //申请原因
        wfrtf[8] = new WorkflowRequestTableField();
        wfrtf[8].setFieldName("shenqingyy");
        wfrtf[8].setFieldValue(pojo.getShenqingyy());
        wfrtf[8].setView(true);
        wfrtf[8].setEdit(true);
        //开票公司 kv转换
        wfrtf[9] = new WorkflowRequestTableField();
        wfrtf[9].setFieldName("kaipiaogs");
        wfrtf[9].setFieldValue(KaiPiaoGSEnum.getKey(pojo.getKaipiaogs()));
        wfrtf[9].setView(true);
        wfrtf[9].setEdit(true);
        //申请日期
        wfrtf[10] = new WorkflowRequestTableField();
        wfrtf[10].setFieldName("shenqingrq");
        wfrtf[10].setFieldValue(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
        wfrtf[10].setView(true);
        wfrtf[10].setEdit(true);
        //表头公司
        wfrtf[11] = new WorkflowRequestTableField();
        wfrtf[11].setFieldName("shenqingrgs");
        wfrtf[11].setFieldValue("1");
        wfrtf[11].setView(true);
        wfrtf[11].setEdit(true);
        //是否ldt发起
        wfrtf[12] = new WorkflowRequestTableField();
        wfrtf[12].setFieldName("ldtfqsqh1");
        wfrtf[12].setFieldValue("1");
        wfrtf[12].setView(true);
        wfrtf[12].setEdit(true);
        //退票发票号
        wfrtf[13] = new WorkflowRequestTableField();
        wfrtf[13].setFieldName("tuipiaofph");
        wfrtf[13].setFieldValue(pojo.getTuipiaofph());
        wfrtf[13].setView(true);
        wfrtf[13].setEdit(true);

        //所属部门
        wfrtf[14] = new WorkflowRequestTableField();
        wfrtf[14].setFieldName("shenqingrbm");
        wfrtf[14].setFieldValue(departmentid);
        wfrtf[14].setView(true);
        wfrtf[14].setEdit(true);

        //业务部门
        wfrtf[15] = new WorkflowRequestTableField();
        wfrtf[15].setFieldName("yewubum");
        wfrtf[15].setFieldValue(departmentid);
        wfrtf[15].setView(true);
        wfrtf[15].setEdit(true);

        //相关附件
        wfrtf[16] = new WorkflowRequestTableField();
        wfrtf[16].setFieldName("xiangguanfj");
        wfrtf[16].setFieldType("http:"+pojo.getXiangguanfjName());
        wfrtf[16].setFieldValue(pojo.getXiangguanfj());
        wfrtf[16].setView(true);
        wfrtf[16].setEdit(true);


        WorkflowRequestTableRecord[] wfrtr = new WorkflowRequestTableRecord[1];
        wfrtr[0] = new WorkflowRequestTableRecord();
        wfrtr[0].setWorkflowRequestTableFields(wfrtf);
        WorkflowMainTableInfo wfmti = new WorkflowMainTableInfo();
        wfmti.setRequestRecords(wfrtr);
        //主表 结束
        //明细表1转化
        int rows = pojo.getItem().size();   //定义明细行数
        wfrtr = new WorkflowRequestTableRecord[rows];//
        for (int i = 0; i < rows; i++) {
            KaiPiaoItemPOJO item=pojo.getItem().get(i);
            wfrtf = new WorkflowRequestTableField[9]; //行字段信息
            //客户名称
            wfrtf[0] = new WorkflowRequestTableField();
            wfrtf[0].setFieldName("kehumcgr");
            wfrtf[0].setFieldValue(item.getKehumc());
            wfrtf[0].setView(true);//字段是否可见
            wfrtf[0].setEdit(true);//字段是否可编辑
            //最终客户
            wfrtf[1] = new WorkflowRequestTableField();
            wfrtf[1].setFieldName("zuizhongkh");
            wfrtf[1].setFieldValue(item.getZuizhongkh());
            wfrtf[1].setView(true);//字段是否可见
            wfrtf[1].setEdit(true);//字段是否可编辑
            //产品编码
            wfrtf[2] = new WorkflowRequestTableField();
            wfrtf[2].setFieldName("chanpinbm");
            wfrtf[2].setFieldValue(item.getChanpinbm());
            wfrtf[2].setView(true);//字段是否可见
            wfrtf[2].setEdit(true);//字段是否可编辑
            //产品名称
            wfrtf[3] = new WorkflowRequestTableField();
            wfrtf[3].setFieldName("zidingycp");
            wfrtf[3].setFieldValue(item.getXiangmumc());
            wfrtf[3].setView(true);//字段是否可见
            wfrtf[3].setEdit(true);//字段是否可编辑
            //数量
            wfrtf[4] = new WorkflowRequestTableField();
            wfrtf[4].setFieldName("shuliang");
            wfrtf[4].setFieldValue(item.getShuliang().toString());
            wfrtf[4].setView(true);//字段是否可见
            wfrtf[4].setEdit(true);//字段是否可编辑
            //单价
            wfrtf[5] = new WorkflowRequestTableField();
            wfrtf[5].setFieldName("danjiahs");
            wfrtf[5].setFieldValue(item.getDanjiahs().toString());
            wfrtf[5].setView(true);//字段是否可见
            wfrtf[5].setEdit(true);//字段是否可编辑
            //备注
            wfrtf[6] = new WorkflowRequestTableField();
            wfrtf[6].setFieldName("beizhu");
            wfrtf[6].setFieldValue(item.getBeizhu());
            wfrtf[6].setView(true);//字段是否可见
            wfrtf[6].setEdit(true);//字段是否可编辑
            //小计(数量乘以单价)
            wfrtf[7] = new WorkflowRequestTableField();
            wfrtf[7].setFieldName("xiaoji");
            wfrtf[7].setFieldValue(item.getXiaoji().toString());
            wfrtf[7].setView(true);//字段是否可见
            wfrtf[7].setEdit(true);//字段是否可编辑

            wfrtf[8] = new WorkflowRequestTableField();
            wfrtf[8].setFieldName("danwei");
            wfrtf[8].setFieldValue(item.getDanwei());
            wfrtf[8].setView(true);//字段是否可见
            wfrtf[8].setEdit(true);//字段是否可编辑

            wfrtr[i] = new WorkflowRequestTableRecord();
            wfrtr[i].setWorkflowRequestTableFields(wfrtf);
        }
        //添加明细表对象
        WorkflowDetailTableInfo detail[] = new WorkflowDetailTableInfo[3];
        detail[0] = new WorkflowDetailTableInfo();
        detail[0].setWorkflowRequestTableRecords(wfrtr);
        //明细表2转化
        if (pojo != null && pojo.getIteTow() != null) {
            int rows2 = pojo.getIteTow().size();   //定义明细行数
            wfrtr = new WorkflowRequestTableRecord[rows2];//
            for (int i = 0; i < rows2; i++) {
                KaiPiaoItemTowPOJO item = pojo.getIteTow().get(i);
                wfrtf = new WorkflowRequestTableField[9]; //行字段信息
                //送检单位
                wfrtf[0] = new WorkflowRequestTableField();
                wfrtf[0].setFieldName("organizationName");
                wfrtf[0].setFieldValue(item.getOrganizationName());
                wfrtf[0].setView(true);//字段是否可见
                wfrtf[0].setEdit(true);//字段是否可编辑
                //姓名
                wfrtf[1] = new WorkflowRequestTableField();
                wfrtf[1].setFieldName("patientName");
                wfrtf[1].setFieldValue(item.getPatientName());
                wfrtf[1].setView(true);//字段是否可见
                wfrtf[1].setEdit(true);//字段是否可编辑
                //采样日期（yyyy-MM-dd）
                wfrtf[2] = new WorkflowRequestTableField();
                wfrtf[2].setFieldName("sampleTakeDate");
                wfrtf[2].setFieldValue(item.getSampleTakeDate());
                wfrtf[2].setView(true);//字段是否可见
                wfrtf[2].setEdit(true);//字段是否可编辑
                //检测名称
                wfrtf[3] = new WorkflowRequestTableField();
                wfrtf[3].setFieldName("itemName");
                wfrtf[3].setFieldValue(item.getItemName());
                wfrtf[3].setView(true);//字段是否可见
                wfrtf[3].setEdit(true);//字段是否可编辑
                //样本类型
                wfrtf[4] = new WorkflowRequestTableField();
                wfrtf[4].setFieldName("sampleTypeName");
                wfrtf[4].setFieldValue(item.getSampleTypeName());
                wfrtf[4].setView(true);//字段是否可见
                wfrtf[4].setEdit(true);//字段是否可编辑
                //检测方
                wfrtf[5] = new WorkflowRequestTableField();
                wfrtf[5].setFieldName("labName");
                wfrtf[5].setFieldValue(item.getLabName());
                wfrtf[5].setView(true);//字段是否可见
                wfrtf[5].setEdit(true);//字段是否可编辑
                //LDT项目编码
                wfrtf[6] = new WorkflowRequestTableField();
                wfrtf[6].setFieldName("projectId");
                wfrtf[6].setFieldValue(item.getProjectId());
                wfrtf[6].setView(true);//字段是否可见
                wfrtf[6].setEdit(true);//字段是否可编辑
                //收款金额
                wfrtf[7] = new WorkflowRequestTableField();
                wfrtf[7].setFieldName("invoiceAmount");
                wfrtf[7].setFieldValue(item.getInvoiceAmount().toString());
                wfrtf[7].setView(true);//字段是否可见
                wfrtf[7].setEdit(true);//字段是否可编辑
                //项目状态
                wfrtf[8] = new WorkflowRequestTableField();
                wfrtf[8].setFieldName("projectState");
                wfrtf[8].setFieldValue(item.getProjectState());
                wfrtf[8].setView(true);//字段是否可见
                wfrtf[8].setEdit(true);//字段是否可编辑

                wfrtr[i] = new WorkflowRequestTableRecord();
                wfrtr[i].setWorkflowRequestTableFields(wfrtf);
            }
        }
        detail[1] = new WorkflowDetailTableInfo();
        detail[1].setWorkflowRequestTableRecords(wfrtr);

        //明细表3转化
        if (pojo != null && pojo.getIteThree() != null) {
            int rows3 = pojo.getIteThree().size();   //定义明细行数
            wfrtr = new WorkflowRequestTableRecord[rows3];//
            for (int i = 0; i < rows3; i++) {
                KaiPiaoItemTowPOJO itemThree = pojo.getIteThree().get(i);
                wfrtf = new WorkflowRequestTableField[9]; //行字段信息
                //送检单位
                wfrtf[0] = new WorkflowRequestTableField();
                wfrtf[0].setFieldName("organizationName");
                wfrtf[0].setFieldValue(itemThree.getOrganizationName());
                wfrtf[0].setView(true);//字段是否可见
                wfrtf[0].setEdit(true);//字段是否可编辑
                //姓名
                wfrtf[1] = new WorkflowRequestTableField();
                wfrtf[1].setFieldName("patientName");
                wfrtf[1].setFieldValue(itemThree.getPatientName());
                wfrtf[1].setView(true);//字段是否可见
                wfrtf[1].setEdit(true);//字段是否可编辑
                //采样日期（yyyy-MM-dd）
                wfrtf[2] = new WorkflowRequestTableField();
                wfrtf[2].setFieldName("sampleTakeDate");
                wfrtf[2].setFieldValue(itemThree.getSampleTakeDate());
                wfrtf[2].setView(true);//字段是否可见
                wfrtf[2].setEdit(true);//字段是否可编辑
                //检测名称
                wfrtf[3] = new WorkflowRequestTableField();
                wfrtf[3].setFieldName("itemName");
                wfrtf[3].setFieldValue(itemThree.getItemName());
                wfrtf[3].setView(true);//字段是否可见
                wfrtf[3].setEdit(true);//字段是否可编辑
                //样本类型
                wfrtf[4] = new WorkflowRequestTableField();
                wfrtf[4].setFieldName("sampleTypeName");
                wfrtf[4].setFieldValue(itemThree.getSampleTypeName());
                wfrtf[4].setView(true);//字段是否可见
                wfrtf[4].setEdit(true);//字段是否可编辑
                //检测方
                wfrtf[5] = new WorkflowRequestTableField();
                wfrtf[5].setFieldName("labName");
                wfrtf[5].setFieldValue(itemThree.getLabName());
                wfrtf[5].setView(true);//字段是否可见
                wfrtf[5].setEdit(true);//字段是否可编辑
                //LDT项目编码
                wfrtf[6] = new WorkflowRequestTableField();
                wfrtf[6].setFieldName("projectId");
                wfrtf[6].setFieldValue(itemThree.getProjectId());
                wfrtf[6].setView(true);//字段是否可见
                wfrtf[6].setEdit(true);//字段是否可编辑
                //收款金额
                wfrtf[7] = new WorkflowRequestTableField();
                wfrtf[7].setFieldName("invoiceAmount");
                wfrtf[7].setFieldValue(itemThree.getInvoiceAmount().toString());
                wfrtf[7].setView(true);//字段是否可见
                wfrtf[7].setEdit(true);//字段是否可编辑
                //项目状态
                wfrtf[8] = new WorkflowRequestTableField();
                wfrtf[8].setFieldName("projectState");
                wfrtf[8].setFieldValue(itemThree.getProjectState());
                wfrtf[8].setView(true);//字段是否可见
                wfrtf[8].setEdit(true);//字段是否可编辑

                wfrtr[i] = new WorkflowRequestTableRecord();
                wfrtr[i].setWorkflowRequestTableFields(wfrtf);
            }
            detail[2] = new WorkflowDetailTableInfo();
            detail[2].setWorkflowRequestTableRecords(wfrtr);
        }



        //创建流程基本对象
        WorkflowBaseInfo wfbi = new WorkflowBaseInfo();
        wfbi.setWorkflowId("3142");
        //创建流程基本信息对象
        WorkflowRequestInfo wri = new WorkflowRequestInfo();
        wri.setRequestName(pojo.getBiaoti());//设置流程名称
        wri.setCreatorId(userid);//创建人ID
        wri.setRequestLevel("0");//流程创建等级
        wri.setWorkflowMainTableInfo(wfmti);//设置主表字段进去
        wri.setWorkflowDetailTableInfos(detail);//添加明细数据
        wri.setWorkflowBaseInfo(wfbi);//设置基本流程基本数据
        wri.setIsnextflow("1");//是否提交到下个节点,如果是0的话,就在开始节点.
        log.info("createWorkflow结束方法体处理--->>>>当前时间:{}", new Date());

        //请求
        String requestid = null;
        String flowNumOA = null;
        try {
            URL url = new URL(oawsurl);
            WorkflowServicePortType workflowServicePortType = new WorkflowServiceLocator().getWorkflowServiceHttpPort(url);
            requestid = workflowServicePortType.doCreateWorkflowRequest(wri, Integer.parseInt(userid));
            WorkflowRequestInfo info = workflowServicePortType.getWorkflowRequest(Integer.parseInt(requestid),Integer.parseInt(userid),Integer.valueOf(requestid));
            flowNumOA = getLiuChengbh(info);

            resultInfo.setRequestid(requestid);
            resultInfo.setFlowNumOA(flowNumOA);

            return resultInfo;
        } catch (Exception e) {
            e.printStackTrace();
            resultInfo.setFlowNum("-100");
            return resultInfo;
        }
    }

    /**
     * 获取oa 用户id bymobile
     */
    private String getOaId(String mobile) throws Exception {
        try {
            String url = smdurl + "/usercenter/getOaUserid?param1=" + mobile;
            String rsp=httpApi.doGet(url);
            Map<String, Object> rspmap = objectMapper.readValue(rsp, Map.class);
            return rspmap.get("oaid").toString();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取oa 用户部门id bymobile
     */
    private String getDepartmentid(String mobile) throws Exception {
        try {
            String url = smdurl + "/usercenter/getOaUserid?param1=" + mobile;
            String rsp=httpApi.doGet(url);
            Map<String, Object> rspmap = objectMapper.readValue(rsp, Map.class);
            return rspmap.get("departmentid").toString();
        } catch (Exception e) {
            return null;
        }
    }
    /**
     * 获取oa 流程编号
     */
    private String getLiuChengbh(WorkflowRequestInfo info) throws Exception {
        try {

            WorkflowRequestTableRecord[] record = info.getWorkflowMainTableInfo().getRequestRecords();
            WorkflowRequestTableField[] workflowRequestTableField =  new WorkflowRequestTableField[38];
            for (WorkflowRequestTableRecord list:record){
                workflowRequestTableField = list.getWorkflowRequestTableFields();
            }
            WorkflowRequestTableField workflowRequestTableField1 = workflowRequestTableField[3];
            return workflowRequestTableField1.getFieldValue();
        } catch (Exception e) {
            return null;
        }
    }





    /**
     * 计算行小记
     */
    private String multiply(Double a,Double b) {
        try {
            DecimalFormat df = new DecimalFormat("#.00");
            Double c=a*b;
            return df.format(c);
        } catch (Exception e) {
            e.printStackTrace();
            return "0.00";
        }
    }
}
